package com.wufun.overseas.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.ConsoleMessage;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;


import com.wufun.baselibrary.download.UtilsMy;
import com.wufun.overseas.R;

import java.io.File;

/**
 * 备注:
 * 此LJWebView继承自Relativielayout,所以会导致丢失一个WebView的属性，如果大家
 * 在项目中需要用到，可是此类中加入，然后调用即可，可参考
 * public void setClickable(boolean value){
 * mWebView.setClickable(value);
 * }
 * 这个方法的定义和调用
 *
 * @author Administrator
 */
public class LJWebView extends RelativeLayout {

    public static int Circle = 0x01;
    public static int Horizontal = 0x02;

    private Context context;

    private WebView mWebView = null;  //
    private ProgressBar progressBar = null;  //水平进度条
    private RelativeLayout progressBar_circle = null;  //包含圆形进度条的布局
    private int barHeight = 4;  //水平进度条的高
    private boolean isAdd = false;  //判断是否已经加入进度条
//    private boolean blockLoadingNetworkImage = true;  //判断是否已经加入进度条
    private int progressStyle = Horizontal;  //进度条样式,Circle表示为圆形，Horizontal表示为水平
    private String appCaceDir;
    private View xCustomView;
    private View xprogressvideo=null;

    public interface FindMethod {
        void noMethod();
        void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback, WebChromeClient chromeClient);
        void onHideCustomView();
        //显示主界面网页
        void showMainWebview();
        void onReceivedTitle(String title);
    }

    private FindMethod findMethod;

    public LJWebView(Context context) {
        super(context);
        this.context = context;
        init();
    }

    public LJWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init();
    }

    public LJWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
        init();
    }

    public void intSet() {
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        mWebView.getSettings().setAppCacheEnabled(true);
        appCaceDir = context.getApplicationContext().getDir("cacheH5", Context.MODE_PRIVATE).getPath();
        mWebView.getSettings().setAppCachePath(appCaceDir);
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
//        mWebView.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
        mWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
//        mWebView.getSettings().setBlockNetworkImage(true);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    }

    private void init() {

        mWebView = new WebView(context);
        this.addView(mWebView, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        mWebView.setBackgroundColor(0x00000000);
        intSet();
        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO Auto-generated method stub
                super.onProgressChanged(view, newProgress);
                if (newProgress>10){
                    if (findMethod!=null){
                        findMethod.showMainWebview();
                    }
                }

                if (newProgress>80){
                    if (progressStyle == Horizontal) {
                        if (progressBar != null)
                            progressBar.setVisibility(View.GONE);
                    } else {
                        if (progressBar_circle != null) {
                            progressBar_circle.setVisibility(View.GONE);
                        }
                    }
                }
                if (newProgress == 100) {
                    if (progressStyle == Horizontal) {
                        if (progressBar != null)
                            progressBar.setVisibility(View.GONE);
                    } else {
                        if (progressBar_circle != null) {
                            progressBar_circle.setVisibility(View.GONE);
                        }
                    }
//                    if(blockLoadingNetworkImage)
//                    {
//                        mWebView.getSettings().setBlockNetworkImage(false);
//                        blockLoadingNetworkImage=false;
//                    }
                } else {
                    if (!isAdd) {
                        if (progressStyle == Horizontal) {
                            progressBar = (ProgressBar) LayoutInflater.from(context).inflate(R.layout.progress_horizontal, null);
                            progressBar.setMax(100);
                            progressBar.setProgress(0);
                            LJWebView.this.addView(progressBar, LayoutParams.FILL_PARENT, barHeight);
                        } else {
//                            progressBar_circle = (RelativeLayout) LayoutInflater.from(context).inflate(R.layout.progress_circle, null);
                            progressBar_circle = (RelativeLayout) LayoutInflater.from(context).inflate(R.layout.loding_layout, null);
                            LJWebView.this.addView(progressBar_circle, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
                        }
                        isAdd = true;
                    }

                    if (progressStyle == Horizontal) {
                        progressBar.setVisibility(View.VISIBLE);
                        progressBar.setProgress(newProgress);
                    } else {
                        progressBar_circle.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                String msg = consoleMessage.message();
                if (msg!=null&&msg.contains("Uncaught ReferenceError") && msg.contains("papaBackPageUp")) {
                    // do something...
                    Log.v("infoo", "xxxxxxxxxxxxxxxxxx   " + msg);
                    if(findMethod!=null) {
                        findMethod.noMethod();
                    }
                }
                Log.d("LjWebView", consoleMessage.message() + " -- From line "
                        + consoleMessage.lineNumber() + " of "
                        + consoleMessage.sourceId());
                return super.onConsoleMessage(consoleMessage);
            }

            CustomViewCallback customViewCallback;

            // 进入全屏的时候
            @Override
            public void onShowCustomView(View view, CustomViewCallback callback) {

                // 赋值给callback
                //如果一个视图已经存在，那么立刻终止并新建一个
                try {
                    if (xCustomView != null) {
                        callback.onCustomViewHidden();
                        return;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                xCustomView = view;
                customViewCallback = callback;
                if(findMethod!=null) {
                    findMethod.onShowCustomView(view, callback, this);
                }
            }

            @Override
            public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) {
                onShowCustomView(view,callback);
            }

            // 退出全屏的时候
            @Override
            public void onHideCustomView() {



                if (xCustomView == null)//不是全屏播放状态
                    return;
                xCustomView = null;
                try {
                    if (customViewCallback != null) {
                        // 隐藏掉
                        customViewCallback.onCustomViewHidden();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if(findMethod!=null) {
                    findMethod.onHideCustomView();
                }
            }

            @Override
            public View getVideoLoadingProgressView() {
                //Log.i(LOGTAG, "here in on getVideoLoadingPregressView");

                if (xprogressvideo == null) {
                    LayoutInflater inflater = LayoutInflater.from(context);
                    xprogressvideo = inflater.inflate(R.layout.video_loading_progress, null);
                }
                return xprogressvideo;
            }

            @Override
            public void onReachedMaxAppCacheSize(long requiredStorage, long quota, WebStorage.QuotaUpdater quotaUpdater) {
                try {
                    UtilsMy.delete(new File(appCaceDir));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                super.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                if(findMethod!=null) {
                    findMethod.onReceivedTitle(title);
                }
                super.onReceivedTitle(view, title);
            }

        });
        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                UtilsMy.downFileFromWeb(context,url,System.currentTimeMillis()+"");
            }
        });
    }

    public void setBarHeight(int height) {
        barHeight = height;
    }

    public void setProgressStyle(int style) {
        progressStyle = style;
    }

    public void setClickable(boolean value) {
        mWebView.setClickable(value);
    }

    public void setUseWideViewPort(boolean value) {
        mWebView.getSettings().setUseWideViewPort(value);
    }

    public void setSupportZoom(boolean value) {
        mWebView.getSettings().setSupportZoom(value);
    }

    public void setBuiltInZoomControls(boolean value) {
        mWebView.getSettings().setBuiltInZoomControls(value);
    }

    public void setJavaScriptEnabled(boolean value) {
        mWebView.getSettings().setJavaScriptEnabled(value);
    }

    public void setCacheMode(int value) {
        mWebView.getSettings().setCacheMode(value);
    }

    public void setWebViewClient(WebViewClient value) {
        mWebView.setWebViewClient(value);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            try {
                mWebView.removeJavascriptInterface("searchBoxJavaBredge_");
            } catch (Exception e) {
            }
        }
    }

    public void loadUrl(String url) {
        mWebView.loadUrl(url);
    }

    @SuppressLint("JavascriptInterface")
    public void addJavascriptInterface(Object object) {
        mWebView.addJavascriptInterface(object, "overseas");
    }
    @SuppressLint("JavascriptInterface")
    public void addJavascriptInterfacewufan(Object object) {
        mWebView.addJavascriptInterface(object, "wufan");
    }

    public WebView getWebView() {
        return mWebView;
    }

    public void setMethodListenter(FindMethod findMethod) {
        this.findMethod = findMethod;
    }
    public void saveState(Bundle outState) {
        mWebView.saveState(outState);
    }
}
